package com.qf.lja.servlet;

import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.Product;
import com.qf.lja.enity.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet(urlPatterns = "/productList.do")
public class ProductListServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取产品数据
        ProductDao productDao = new ProductDao();
//        List<Product> productList = productDao.queryAllProductr();

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.sendRedirect("login.jsp");
        }

        //分页
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");
        System.out.println("deBug");
        int pageSizeInt = 8;
        if (pageSize != null && !"".equals(pageSize)) {
            pageSizeInt = Integer.parseInt(pageSize);
            if (pageSizeInt < 1 || pageSizeInt > 100) {
                pageSizeInt = 10;   // 超出页面范围就设置默认值
            }
        }

        int currentPageInt = 1; // 当前页数
        int rows = productDao.countProducts(); // 获取产品总数
        int totalPage = (int) Math.ceil(1.0 * rows / pageSizeInt); // 计算总页数
        if (currentPage != null && !"".equals(currentPage)) {
            currentPageInt = Integer.parseInt(currentPage);
            if (currentPageInt < 1 || currentPageInt > totalPage) {
                currentPageInt = 1; // 当前页超出范围，使用默认值
            }
        }

        List<Product> productList = productDao.getProductsPage(currentPageInt, pageSizeInt); // 获取分页产品列表


        // 将产品列表存储到请求属性中

        request.setAttribute("pageSize", pageSizeInt);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("currentPage", currentPageInt);
        request.setAttribute("productList", productList); // 设置产品列表属性

        // 转发请求到goodsList.jsp页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("/goodsList.jsp");
        dispatcher.forward(request, response);
    }
}
